//
//  CouponListViewController.m
//  ForestPack
//
//  Created by 郑洲 on 2018/7/5.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "CouponListViewController.h"
#import "CouponListCell.h"

@interface CouponListViewController ()<UIScrollViewDelegate, UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UIView *moveLine;
@property (nonatomic, strong) UIButton *selectBtn;
@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, assign) NSInteger isUse;

@property (nonatomic,strong)  NSMutableArray  * dataArray;
@property (nonatomic,strong)  NSMutableArray  * undataArray;

@end

@implementation CouponListViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setShadowImage:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"优惠券";
    self.isUse = 0;
    self.dataArray = [NSMutableArray array];
    self.undataArray = [NSMutableArray array];
    
    [self setTopBar];
    [self setUI];
}

- (void)setTopBar {
    UIView *topBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(30))];
    topBar.backgroundColor = RGB_COLOR(235, 67, 90);
    [self.view addSubview:topBar];
    
    NSArray *nameArr = @[@"未使用",@"已使用"];
    for (int i = 0; i < nameArr.count; i++) {
        UIButton *typeBtn = [[UIButton alloc] initWithFrame:CGRectMake(i * SCREEN_WIDTH / 2, 0, SCREEN_WIDTH / 2, ScreenX375(30))];
        [typeBtn setTitle:nameArr[i] forState:UIControlStateNormal];
        [typeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        [typeBtn setTitleColor:RGBACOLOR(255, 255, 255, 0.6) forState:UIControlStateNormal];
        typeBtn.titleLabel.font = Kfont(16);
        typeBtn.tag = 100 + i;
        if (i == 0) {
            typeBtn.selected = YES;
            _selectBtn = typeBtn;
        }
        [typeBtn addTarget:self action:@selector(typeClick:) forControlEvents:UIControlEventTouchUpInside];
        [topBar addSubview:typeBtn];
    }
    
    self.moveLine = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenX375(30) - 2, SCREEN_WIDTH / 2, 2)];
    self.moveLine.backgroundColor = [UIColor whiteColor];
    [topBar addSubview:self.moveLine];
}

- (void)typeClick:(UIButton *)button {
    _selectBtn.selected = NO;
    button.selected = YES;
    _selectBtn = button;
    _isUse = button.tag - 100;
    if (button.tag == 101 && _dataArray.count == 0) {
        BaseTableView *tableView = [self.view viewWithTag:201];
        [tableView.mj_header beginRefreshing];
    }
    [UIView animateWithDuration:0.3 animations:^{
        self.moveLine.frame = CGRectMake((button.tag - 100) * SCREEN_WIDTH / 2, ScreenX375(30) - 2, SCREEN_WIDTH / 2, 2);
    }];
    [_scrollView setContentOffset:CGPointMake((button.tag - 100) * SCREEN_WIDTH, 0) animated:YES];
}

- (void)setUI {
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, ScreenX375(30), SCREEN_WIDTH, SCREEN_HEIGHT - ScreenX375(30))];
    _scrollView.showsVerticalScrollIndicator = false;
    _scrollView.showsHorizontalScrollIndicator = false;
    _scrollView.pagingEnabled = true;
    _scrollView.delegate = self;
    _scrollView.contentSize = CGSizeMake(SCREEN_WIDTH * 2, 0);
    [self.view addSubview:_scrollView];
    
    for (int i = 0; i < 2; i++) {
        BaseTableView *tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(i * SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT - ScreenX375(30))];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.backgroundColor = [UIColor whiteColor];
        tableView.tag = 200 + i;
        tableView.rowHeight = ScreenX375(104);
        
        [_scrollView addSubview:tableView];
        
        __weak typeof(self) weakSelf = self;
        tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            NSString *url = [NSString stringWithFormat:@"%@app/coupon_info",REQUESTHEADER];
            NSDictionary *dict = @{@"token":[FPLoginAndRegisterTools getToken],@"state":@"1"};
            if (weakSelf.isUse == 1) {
                dict = @{@"token":[FPLoginAndRegisterTools getToken],@"state":@"2"};
            }
            
            [HttpManager postHttpRequestByPost:url andParameter:dict success:^(id successResponse) {
                NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
                if ([status isEqualToString:@"1"]) {
                    [tableView.mj_header endRefreshing];
                    NSError *error;
                    
                    if (weakSelf.isUse == 0) {
                        [self.undataArray removeAllObjects];
                        // 成功
                        for (NSDictionary *dic in successResponse[@"data"]) {
                            CouponModel *model = [[CouponModel alloc] initWithDictionary:dic error:&error];
                            model.isUsed = @"0";
                            if (model != nil) {
                                [self.undataArray addObject:model];
                            }
                        }
                    }else {
                        [self.dataArray removeAllObjects];
                        // 成功
                        for (NSDictionary *dic in successResponse[@"data"]) {
                            CouponModel *model = [[CouponModel alloc] initWithDictionary:dic error:&error];
                            model.isUsed = @"1";
                            if (model != nil) {
                                [self.dataArray addObject:model];
                            }
                        }
                    }
                    [tableView reloadData];
                    
                }else{
                    [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
                }
            } andFailure:^(id failureResponse) {
                [tableView.mj_header endRefreshing];
                [HttpManager showFail];
            }];
        }];
        
        if (i == 0) {
            [tableView.mj_header beginRefreshing];
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView.tag == 200) {
        return _undataArray.count;
    }
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CouponListCell *cell = [CouponListCell cellWithTableView:tableView andIndexPath:indexPath];
    if (tableView.tag == 200) {
        cell.couponModel = _undataArray[indexPath.row];
    }else {
        cell.couponModel = _dataArray[indexPath.row];
    }
    return cell;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == _scrollView) {
        NSInteger index = scrollView.contentOffset.x / SCREEN_WIDTH;
        
        UIButton *button = [self.view viewWithTag:index + 100];
        _selectBtn.selected = NO;
        button.selected = YES;
        _selectBtn = button;
        [UIView animateWithDuration:0.3 animations:^{
            self.moveLine.frame = CGRectMake((button.tag - 100) * SCREEN_WIDTH / 2, ScreenX375(30) - 2, SCREEN_WIDTH / 2, 2);
        }];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    NSInteger index = scrollView.contentOffset.x / SCREEN_WIDTH;
    
    UIButton *button = [self.view viewWithTag:index + 100];
    _selectBtn.selected = NO;
    button.selected = YES;
    _selectBtn = button;
    _isUse = button.tag - 100;
    if (button.tag == 101 && _dataArray.count == 0) {
        BaseTableView *tableView = [self.view viewWithTag:201];
        [tableView.mj_header beginRefreshing];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
